
class Snake{

    element  : HTMLElement;
    head : HTMLElement;
    bodies : HTMLCollection;

    constructor(){
        this.element = document.getElementById("snake") !;
        this.head = document.querySelector("#snake > div") as HTMLElement;
        this.bodies = this.element.getElementsByTagName("div") ;
    }

    get X() {
        return this.head.offsetLeft;
    }

    get Y() {
        return this.head.offsetTop;
    }

    set X(x: number) {
        if (x == this.X) {
            return ;
        }
        if(x < 0 || x > 290) {
            // snake is dead
            throw Error();
        }
        this.head.style.left = x + 'px';
    }

    set Y(y: number) {
        if (y == this.Y) {
            return ;
        }
        if(y < 0 || y > 290) {
            throw Error();
        }
        this.head.style.top = y + 'px';

    }

    addBody() {
        this.element.insertAdjacentHTML("beforeend" , "<div></div>")
    }

    moveBody(){

        for (let i = this.bodies.length - 1 ; i > 0 ; i --) {
            let x = (this.bodies[i-1] as HTMLElement).offsetLeft ;
            let y = (this.bodies[i-1] as HTMLElement).offsetTop ;
            (this.bodies[i] as HTMLElement).style.left = x + 'px';
            (this.bodies[i] as HTMLElement).style.top = y + 'px';
        }
    }

    checkSelfHit(): boolean{
        for(let i = 1 ; i < this.bodies.length ; i++){
            if (this.X === (this.bodies[i] as HTMLElement).offsetLeft && this.Y === (this.bodies[i] as HTMLElement).offsetTop ){
                return true ;
            }
        }
        return false ;
    }
}

export  default Snake ;